﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;

namespace Minion.Web.Data.Service.Concrete
{
    public class LocationService : ILocationService
    {
        public IList<Location> GetLocationDetails(double latitude, double longitude)
        {
            //Get all locations within 10m of this lat and long
            var context = new MinionEntities();
            var allLocations = context.Locations.ToList();
            var locations = allLocations.Where(l =>
                                               Math.Acos(Math.Sin(latitude) * Math.Sin(l.Latitude) +
                                                         Math.Cos(latitude) * Math.Cos(l.Latitude) *
                                                         Math.Cos(l.Longitude - (longitude)))*6371 <= 3);
            return locations.ToList();
        }

        public void AddLocationToDb(Location location)
        {
            var context = new MinionEntities();
            //find location with the same lat and long
            var foundLocation =
                context.Locations.Where(l => l.Latitude == location.Latitude && l.Longitude == location.Longitude);
            if(foundLocation.Any())
            {
                foreach (var locationItem in location.LocationItems)
                {
                    var loc = context.Locations.Find(foundLocation.First().Id);
                    loc.LocationItems.Add(locationItem);
                }
            }
            else
            {
                context.Locations.Add(location); 
            }
            context.SaveChanges();
        }

        public IList<Location> GetAllLocations()
        {
            var context = new MinionEntities();
            return context.Locations.ToList();
        }
        
    }
}